package com.xlh.virtualization.job.scheduler;

import com.xlh.virtualization.dao.ContainerMapper;
import com.xlh.virtualization.dao.ImageAllocationMapper;
import com.xlh.virtualization.dao.ImageAllocationSlaveMapper;
import com.xlh.virtualization.dao.ImageMapper;
import com.xlh.virtualization.domain.example.ContainerExample;
import com.xlh.virtualization.domain.example.ImageAllocationExample;
import com.xlh.virtualization.domain.example.ImageAllocationSlaveExample;
import com.xlh.virtualization.domain.example.ImageExample;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 定时清理三十天以上的逻辑删除数据（虚拟化部分）
 *
 * @author cheer
 */
@Component
@Slf4j
public class DBCleanJob {

    @Autowired
    private ContainerMapper containerMapper;

    @Autowired
    private ImageMapper imageMapper;

    @Autowired
    private ImageAllocationMapper imageAllocationMapper;

    @Autowired
    private ImageAllocationSlaveMapper imageAllocationSlaveMapper;

    /**
     * 每天凌晨2点执行清理定时任务
     */
    @Scheduled(cron = "0 0 2 * * *")
    public void containerDelete() {
        try {
            log.info("开始执行定时清理脏数据（虚拟化）");

            cleanContainer();
            cleanImage();
            cleanImageAllocation();

            log.info("执行定时清理脏数据（虚拟化）完毕");
        } catch (Exception e) {
            log.error("执行定时清理脏数据（虚拟化）异常", e);
        }
    }

    /**
     * 清理容器数据
     */
    private void cleanContainer() {
        ContainerExample example = new ContainerExample();
        example.or().andDeletedEqualTo(true)
                .andUpdateTimeLessThanOrEqualTo(DateUtils.addDays(new Date(), -30));
        containerMapper.deleteByExample(example);
    }

    /**
     * 清理镜像数据
     */
    private void cleanImage() {
        ImageExample example = new ImageExample();
        example.or().andDeletedEqualTo(true)
                .andUpdateTimeLessThanOrEqualTo(DateUtils.addDays(new Date(), -30));
        imageMapper.deleteByExample(example);
    }

    /**
     * 清理镜像分配数据
     */
    private void cleanImageAllocation() {
        ImageAllocationExample example = new ImageAllocationExample();
        example.or().andDeletedEqualTo(true)
                .andUpdateTimeLessThanOrEqualTo(DateUtils.addDays(new Date(), -30));
        imageAllocationMapper.deleteByExample(example);

        ImageAllocationSlaveExample slaveExample = new ImageAllocationSlaveExample();
        slaveExample.or().andDeletedEqualTo(true)
                .andUpdateTimeLessThanOrEqualTo(DateUtils.addDays(new Date(), -30));
        imageAllocationSlaveMapper.deleteByExample(slaveExample);
    }
}
